<?php
/**
 *  扩展字段控制器
 */
namespace app\admin\controller;
use think\Db;
use app\admin\model\ModelM as ModelMModel;
use app\admin\model\Extfieldm as ExtfieldmModel;
class Extfiel extends Common
{
    private $model;
	private $PageCount;
	private $modelm;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ExtfieldmModel();
		$this->modelm = new ModelMModel();
		$this->PageCount=20;
    }

    // 扩展字段列表
    public function index()
    {
		$UrlParam=input();
		$mcode = intval(input('mcode'));
		if(!$mcode){
			$UrlParam['mcode']=false;
		}
		if ($field = input('field') &&$keyword = trim(input('keyword'))) {
			$UrlParam['field']=$keyword;
			$result = $this->model->findExtField($UrlParam,$this->PageCount);
		} else {
			$result = $this->model->getList($UrlParam,$this->PageCount);
		}
		// 内容模型
		$this->assign('extfields', $result);
		$this->assign('UrlParam', $UrlParam);
		$this->assign('models', $this->modelm->getSelect());
        return $this->fetch();
    }
    // 扩展字段增加
    public function add()
    {
        if($this->request->isPost()) {
            // 获取数据
            $mcode = input('mcode/s');
            $name = input('name/s');
            $type = input('type/d');
			$isture = input('isture');
            if (! ! $value = input('value')) {
                $value = str_replace("\r\n", ",", $value); // 替换回车
                $value = str_replace("，", ",", $value); // 替换中文逗号分割符
            }
            $description = input('description/s');
            $sorting = input('sorting/d');
            if (! $mcode) {
				alert('请选择模型','back');
            }
            if (! $name) {
				alert('字段名称不能为空！','back');
            } else {
                $name = "ext_" . $name;
            }

            if (! $type) {
				alert('字段类型不能为空！','back');
            }

            if (! $description) {
				alert('字段描述不能为空！','back');
            }

            // 构建数据
            $data = array(
                'mcode' => $mcode,
                'name' => $name,
                'type' => $type,
                'value' => $value,
                'description' => $description,
                'sorting' => $sorting,
				'isture' => $isture
            );

            // 字段类型及长度
            switch ($type) {
                case '2': // 多行
                    $mysql = 'text(0)';
                    break;
                case '7': // 时间日期
                    $mysql = 'datetime';
                    break;
                case '8': // 编辑器
                    $mysql = 'text(0)';
                    break;
                default:
                    $mysql = 'varchar(200)';
            }
			if ($this->model->checkExtField($name)) {
				// 字段存在且已使用则 报错
				alert('字段已经存在，不能重复添加！','back');
            }
            // 字段不存在时创建
            if (! $this->model->isExistField($name)) {
                 $result = $this->model->amd("ALTER TABLE cb_content_ext ADD $name $mysql NULL COMMENT '$description'");
            }

            // 执行扩展字段记录添加
            if ($this->model->addExtField($data)) {
                    $this->success('新增成功！', url('/Extfiel/index'));
            } else {
                $this->error('新增失败！');
            }
        } else {
            // 内容模型
            $this->assign('models', $this->modelm->getSelect());
            $this->assign('add', true);
            return $this->fetch('index');
        }
    }

    // 扩展字段删除
    public function del()
    {
		if($this->request->isPost())
        {
            $this->delmore();

        }elseif($this->request->isGet()) {
			 if (! $id = input('id/s')) {
				alert('传递的参数值错误！','back');
			}
			$name = $this->model->getExtFieldName($id);
			if ($this->model->delExtField($id)) {
				// mysql数据库执行字段删除
				if ($name) {
					$result = $this->model->amd("ALTER TABLE cb_content_ext DROP COLUMN $name");
				}
				alert('删除成功！','back');
			} else {
				alert('删除失败！','back');
			}
		}
    }
	 //批量删除记录
    private function delmore()
    {
        $DelID=input('post.Del/a');
        if(!empty($DelID))
        {
			foreach($DelID as $key=>$val){
				$name = $this->model->getExtFieldName($val);
				if ($this->model->delExtField($val)) {
					$result = $this->model->amd("ALTER TABLE cb_content_ext DROP COLUMN $name");
				}
			}
        }
        alert('此记录批量删除成功','back');
        exit;
    }

    // 扩展字段修改
    public function mod()
    {
		$biaodantype=array();
		$UrlParam=input();
		$id = intval($UrlParam['id']);
        if (!$id) {
            $this->error('传递的参数值错误！', - 1);
        }
		$this->assign('UrlParam', $UrlParam);
        // 单独修改状态
        if (($field = input('field')) && ! is_null($value = input('value'))) {
			$info[$field]=$value;
            if ($this->model->modExtField($id,$info)) {
                location(- 1);
            } else {
                alert('修改失败！','back');
            }
        }
        // 修改操作
        if($this->request->isPost()) {
            // 获取数据
            $mcode = input('mcode/s');
            $type = input('type/s');
			$name = input('name/s');
			$isture = input('isture/d');
            if (! ! $value = input('value')) {
                $value = str_replace("\r\n", ",", $value); // 替换回车
                $value = str_replace("，", ",", $value); // 替换中文逗号分割符
            }
            $description = input('description');
            $sorting = input('sorting/s');
             if (! $mcode) {
				alert('请选择模型','back');
            }
			if (! $name) {
				alert('字段名称不能为空！','back');
			}
            if (! $description) {
                alert('字段描述不能为空！','back');
            }

            // 构建数据
            $data = array(
                'mcode' => $mcode,//关联分类
                'type' => $type,//类型
                'value' => $value,
				'name' => $name,
                'description' => $description,
                'sorting' => $sorting,
				'isture' => $isture
            );
            // 执行修改
            if ($this->model->modExtField($id, $data)) {
                 $this->success('修改成功！',url('/Extfiel/index'));
            } else {
                location(- 1);
            }
        } else {
            // 调取修改内容
            $this->assign('mod', true);
            if (! $result = $this->model->getExtField($id)) {
                $this->error('编辑的内容已经不存在！', - 1);
            }
            // 内容模型
            $this->assign('models', $this->modelm->getSelect());
            $this->assign('extfield', $result);
            return $this->fetch();
        }
    }
	//批量排序
    public function sort()
    {
        $SortArr=input('post.Sort/a');
        if(!empty($SortArr))
        {
            $TempArr=[];$SortID=[];$SortIDStr='';
            foreach ($SortArr as $key=>$val)
            {
                $SortID[]=$key;
                $TempArr[]=['id'=>$key,'sorting'=>$val];
            }
            if(!empty($SortID)){$SortIDStr=implode(',',$SortID);}
            $this->model->saveAll($TempArr);
        }
        alert('排序更新成功','back');
        exit;
    }
}